/* This function takes an ordinary matrix and returns it in cmtrx format by "cm"
   after removing "continuous" zeros from it's rows. */

# include "scene.h"
# include <stdlib.h>

extern short cmtrx_make(double **mtrx, unsigned short nrows, unsigned short ncols, struct cmtrx *cm)
  {
   short istart, iend;
   unsigned short i, j;

   if(mtrx == (double **)0) return -20;
   if(cm == (struct cmtrx *)0) return -21;

   cm->nrows = nrows;
   cm->ncols = ncols;

/* These memory needs to be freed up outside of this function. */
   cm->istart = (short *)malloc(sizeof(double)*nrows); /* Beginning of the stencil. */
   cm->iend = (short *)malloc(sizeof(double)*nrows); /* End of the stencil. */
   cm->mtrx = (double **)malloc(sizeof(double *)*nrows); /* The co-efficient matrix. */

/* Extracting the non-zero elements from the matrix. */
   for(i = 0; i < nrows; i++)
     {
      istart = iend = -1;
      for(j = 0; j < ncols; j++)
        {
         if(istart < 0) if(mtrx[i][j] != (double)0) istart = j;
         if(istart >= 0)
            {
             if(mtrx[i][j] == (double)0) { if(iend < 0) iend = j-1; }
             else iend = -1;
            }
        }

      if(iend < 0) if(istart >= 0) iend = ncols-1;
      if(istart < 0) return -22; //All the elements in this row is zero.

      cm->istart[i] = istart;
      cm->iend[i] = iend;
      cm->mtrx[i] = (double *)malloc(sizeof(double)*(iend-istart+1));

   /* Copy the non-zero elements into the co-efficient matrix. Size of the p-th row
      will be: "iend[p]-istart[p]+1". It will correspond to istart[p]~iend[p]-th
      elements of the {u}-vector. */
      for(j = 0; j <= iend-istart; j++) cm->mtrx[i][j] = mtrx[i][istart+j];
     }

   return 20;
  }
